//
//  FirstViewController.m
//  Client
//
//  Created by 顾悦 on 16/3/21.
//
//

#import "HomeViewController.h"

#import "RegionWebService.h"
#import "CommunityWebService.h"
#import "BannerWebService.h"
#import "InformationWebService.h"
#import "BeanWebService.h"
#import "BizMenuWebService.h"
#import "MenuSignWebService.h"

#import "City.h"
#import "Community.h"
#import "Banner.h"
#import "BizMenu.h"
#import "Information.h"
#import "MenuSign.h"

#import "ThemeColor.h"
#import "LoadingView.h"

#import "UIImageView+OnlineImage.h"
#import "SVPullToRefresh.h"

#import "HomeBannersCollectionViewCell.h"
#import "HomeButtonsCollectionViewCell.h"
#import "HomeInfoHeaderCollectionViewCell.h"
#import "HomeInfosCollectionViewCell.h"

#import "CitySelectorViewController.h"
#import "CommunitySelectorViewController.h"
#import "ProjectsHelpersViewController.h"

#import "ClientWebViewController.h"

#import "UserInfoController.h"
#import "HomeBizMenusCell.h"


#import "BulkOrderViewController.h"
#import "SDCycleScrollView.h"
#import "AppConfiguration.h"

#define serviceId  @"d5f6f607-e308-4e71-b729-42465a8aae01"
//#define baseUrl @"http://testyyzbhc.einwin.com/pages"

@import CoreLocation;

@interface HomeViewController () <HomeButtonsDelegate, CitySelectorDelegate, CommunitySelectorDelegate, CLLocationManagerDelegate, SDCycleScrollViewDelegate,HomeBizMenusCellDelegate>

@property (nonatomic, copy) City *city;
@property (nonatomic, copy) Community *community;
@property (nonatomic, weak) IBOutlet UIButton *titleButton;

@property (nonatomic, weak) IBOutlet UICollectionView *collectionView;

@property (nonatomic, strong) RegionWebService *regionWebService;
@property (nonatomic, strong) CommunityWebService *communityWebService;
@property (nonatomic, strong) BannerWebService *bannerWebService;
@property(nonatomic,strong)MenuSignWebService*menuSignWebService;
@property (nonatomic, strong) InformationWebService *informationWebService;
@property (nonatomic, strong) BeanWebService *beanWebService;
@property (nonatomic, strong) BizMenuWebService *bizMenuWebService;

@property (strong, nonatomic) NSArray<Banner *> *banners;
@property (strong, nonatomic) NSArray<HomeButton *> *buttons;
@property (strong, nonatomic) NSArray<BizMenu *> *menus;

@property(strong,nonatomic)BizMenu *publicMenus;

@property (nonatomic,strong)MenuSign *menuSign;
@property (strong, nonatomic) NSMutableArray<Information *> *infos;
@property (nonatomic) NSUInteger pageIndex;
@property (nonatomic) NSUInteger pageSize;

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic) NSTimeInterval lastUpdateTime;
@property (nonatomic) CLLocationDegrees latitude;
@property (nonatomic) CLLocationDegrees longitude;


@property (nonatomic, strong) SDCycleScrollView *bannerView;


@end

@implementation HomeViewController

#pragma mark - 

- (void)pushLoginViewControllerCompletionHandler:(CompletionHandler)completionHandler {
    [self performSegueWithIdentifier:@"pushLoginView" sender:completionHandler];
}

#pragma mark - Properties

- (void)setCity:(City *)city {
    _city = city;
    [UserInfoController setDefaultCityID:city.ID];
    [UserInfoController setDefaultCityName:city.name];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.navigationItem.leftBarButtonItem.title = [NSString stringWithFormat:@"%@ ▾", city.name];
    });
}

- (void)setCommunity:(Community *)community {
    _community = community;
    [UserInfoController setDefaultCommunityID:community.ID];
    [UserInfoController setDefaultCommunityName:community.name];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.titleButton setTitle:community.name forState:UIControlStateNormal];
        [self.titleButton sizeToFit];
    });
    if (self.community.ID) {
        [self fetchBizMenus];
    }
}

- (RegionWebService *)regionWebService {
    if (!_regionWebService) {
        _regionWebService = RegionWebService.new;
    }
    
    return _regionWebService;
}

- (CommunityWebService *)communityWebService {
    if (!_communityWebService) {
        _communityWebService = CommunityWebService.new;
    }
    
    return _communityWebService;
}

- (BannerWebService *)bannerWebService {
    if (!_bannerWebService) {
        _bannerWebService = BannerWebService.new;
    }
    
    return _bannerWebService;
}

- (InformationWebService *)informationWebService {
    if (!_informationWebService) {
        _informationWebService = InformationWebService.new;
    }
    
    return _informationWebService;
}

-(MenuSignWebService *)menuSignWebService{
    if (!_menuSignWebService) {
        _menuSignWebService = MenuSignWebService.new;
    }
    return _menuSignWebService;
}

- (BeanWebService *)beanWebService {
    if (!_beanWebService) {
        _beanWebService = BeanWebService.new;
    }
    
    return _beanWebService;
}

- (BizMenuWebService *)bizMenuWebService {
    if (!_bizMenuWebService) {
        _bizMenuWebService = BizMenuWebService.new;
    }
    
    return _bizMenuWebService;
}

- (NSArray<Banner *> *)banners {
    if (!_banners) {
        _banners = NSMutableArray.new;
    }
    
    return _banners;
}

- (NSArray<HomeButton *> *)buttons {
    if (!_buttons) {
        NSMutableArray *bs = NSMutableArray.new;
        [bs addObject:[[HomeButton alloc] initWithIcon:@"purchase_icon" name:@"惠购" selector:@selector(showPromotion)]];
        NSLog(@"%@",_menuSign.CouponsSign);
        if ([_menuSign.CouponsSign isEqual:@"1"]) {
            [bs addObject:[[HomeButton alloc] initWithIcon:@"02" name:@"领券中心" selector:@selector(tryToShowCouponCenter)]];
        }else{
        [bs addObject:[[HomeButton alloc] initWithIcon:@"ticketCenter_icon" name:@"领券中心" selector:@selector(tryToShowCouponCenter)]];
        }
        [bs addObject:[[HomeButton alloc] initWithIcon:@"publicReqair_icon" name:@"公区维修" selector:@selector(tryToShowReward)]];
        [bs addObject:[[HomeButton alloc] initWithIcon:@"collarPoint_icon" name:@"领帮豆" selector:@selector(tryToCollectBeans)]];
        _buttons = bs;
    }
    
    return _buttons;
}

- (NSArray<BizMenu *> *)menus {
    if (!_menus) {
        NSMutableArray *ms = NSMutableArray.new;
        _menus = ms;
    }
    
    return _menus;
}


//
//- (NSUInteger)pageIndex {
//    if (_pageIndex == 0) {
//        _pageIndex = 1;
//    }
//    
//    return _pageIndex;
//}

- (NSUInteger)pageSize {
    if (_pageSize == 0) {
        _pageSize = 4;
    }
    
    return _pageSize;
}

- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = CLLocationManager.new;
        _locationManager.delegate = self;
    }
    
    return _locationManager;
}


//fmy
- (void)updateBannerNoticeView
{
    if ([self.banners count]) {
        if (!_bannerView ) {
            _bannerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, ScreenWidth, 186) delegate:self placeholderImage:nil];
            
            _bannerView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
            _bannerView.currentPageDotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
            _bannerView.infiniteLoop =YES;
            _bannerView.autoScrollTimeInterval =5;
        }
        
        NSMutableArray *pics =[NSMutableArray arrayWithCapacity:0];
        //        NSInteger count =self.homePageData.banners.count < 6 ? self.homePageData.banners.count : 6;
        for ( int i=0;i<_banners.count;i++ ) {
            Banner *banner =_banners[i];
            [pics addObject:banner.imagePath];
        }
        self.bannerView.imageURLStringsGroup =pics;
        
    } else {
        [_bannerView removeFromSuperview];
        _bannerView = nil;
        _bannerView.height = 0;
    }
}


- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"点击了第几个>>>>>  %ld", (long)index);
    if (index >= _banners.count) {
        return;
    }
    Banner *banner =_banners[index];
    if ([banner.imageType integerValue] == 0) {
        return;
    }else if ([banner.imageType integerValue] == 1){
    
        //跳转h5页面
        
        ClientWebViewController *webViewController = ClientWebViewController.new;
        webViewController.HTMLURL = banner.linkUrl;
        webViewController.hidesBottomBarWhenPushed = YES;
        [[self tabBarController].viewControllers.firstObject pushViewController:webViewController animated:YES];
        
    
    }else if ([banner.imageType integerValue] == 2){
        
        //跳转网页地址
        ClientWebViewController *webViewController = ClientWebViewController.new;
        webViewController.HTMLURL = banner.linkUrl;
        webViewController.hidesBottomBarWhenPushed = YES;
        [[self tabBarController].viewControllers.firstObject pushViewController:webViewController animated:YES];

        
    }

    
    
    NSLog(@"%@",banner);
    
}

#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [ThemeColor lightGrayBGColor];
    
    [self setupDefaultCityAndCommunity];
    
    self.navigationItem.titleView = self.titleButton;
    [self menusign];
    [self registerCellIdentifiers];

    [self fetchInfos];
//    [self fetchBanners];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payFinished:) name:@"NotificationNamePayFinished" object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NotificationNamePayFinished" object:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self setupInfiniteScrolling];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    UIViewController *destinationViewController = segue.destinationViewController;
    destinationViewController.hidesBottomBarWhenPushed = YES;
    if ([destinationViewController isKindOfClass:[CitySelectorViewController class]]) {
        CitySelectorViewController *citySelectorViewController = (CitySelectorViewController *)destinationViewController;
        citySelectorViewController.selectedCity = self.city;
        citySelectorViewController.delegate = self;
    }
    else if ([destinationViewController isKindOfClass:[CommunitySelectorViewController class]]) {
        CommunitySelectorViewController *communitySelectorViewController = (CommunitySelectorViewController *)destinationViewController;
        if (!self.community.cityID.length) {
            self.community.cityID = self.city.ID;
        }
        communitySelectorViewController.selectedItem = self.community;
        communitySelectorViewController.delegate = self;
    }
    else if ([destinationViewController isKindOfClass:[ClientLoginViewController class]]) {
        ClientLoginViewController *loginViewController = (ClientLoginViewController *)destinationViewController;
        loginViewController.completionHandler = (CompletionHandler)sender;
    }
}

#pragma mark - Networking

- (void)fetchDetaultCity {   //获取默认的城市  请求banner接口中会用到
    [self.regionWebService getDefaultCity:@"1"
                                 pageSize:@"1"
                                longitude:@(self.longitude)
                                 latitude:@(self.latitude)
                        completionHanlder:^(NSArray *items, NSError *error) {
                            if (error) {
                                self.city = [[City alloc] initWithName:@"请选择"];
                                self.community = [[Community alloc] initWithName:@"请选择"];
                            } else {
                                self.city = [[City alloc] initWithDictionary:items.firstObject];
                                [self fetchDefaultCommunity];
                            }
                        }];
}

- (void)fetchDefaultCommunity {
    [self.regionWebService getCommunitiesByCityID:self.city.ID
                                              pageNo:@"1"
                                            pageSize:@"1"
                                           longitude:@(self.longitude)
                                            latitude:@(self.latitude)
                                   completionHanlder:^(NSArray *items, NSError *error) {
                                       if (error) {
                                           self.community = [[Community alloc] initWithName:@"请选择"];
                                       } else {
                                           self.community = [[Community alloc] initWithDictionary:[items lastObject]];
                                       }
                                       [self fetchBanners];
                                        [self fetchInfos];
                                   }];
}

- (void)fetchBizMenus {
    [LoadingView show];
    [self.bizMenuWebService getBizMenusByCommunity:self.community.ID completionHanlder:^(NSArray *items, NSError *error) {
        NSMutableArray<BizMenu *> *menus = NSMutableArray.new;
        
        NSMutableArray *copyArray =[NSMutableArray arrayWithArray:items];
        
        [items enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if([obj[@"ModuleName"] isEqual:@"公区维修"] && [obj[@"Level"] intValue]==1){  //一排按钮之公区维修数据
                _publicMenus = [[BizMenu alloc]initWithDictionary:obj];
            }
            
            if ([obj[@"ParentId"] isEqualToString: @""]) {
                [menus addObject:[[BizMenu alloc] initWithDictionary:obj]];//一级
            }
        }];
        
        [items enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [menus enumerateObjectsUsingBlock:^(BizMenu * _Nonnull obj1, NSUInteger idx1, BOOL * _Nonnull stop) {
                if ([obj[@"ParentId"] isEqualToString: obj1.Id]) {
                    if ([obj[@"Level"] integerValue] == 2) {
                        [obj1.subclassArray addObject:[[BizMenu alloc] initWithDictionary:obj]];
                    }
                    if ([obj[@"Level"] integerValue] == 3) {
                        [obj1.subclassArray1 addObject:[[BizMenu alloc] initWithDictionary:obj]];
                    }
                }
            }];
        }];
        
        [menus enumerateObjectsUsingBlock:^(BizMenu * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                for (int i = 0; i<6; i++) {
                    NSDictionary *dic = @{@"Level":[NSNumber numberWithInt:2],@"ParentId":obj.Id,@"ModuleName":@"",@"Id":@"112233"};
                    NSDictionary *dic1 = @{@"Level":[NSNumber numberWithInt:3],@"ParentId":@"112233",@"ModuleName":@"",@"Id":@""};
                    [obj.subclassArray addObject:[[BizMenu alloc] initWithDictionary:dic]];
                    [obj.subclassArray1 addObject:[[BizMenu alloc] initWithDictionary:dic1]];
                }

        }];
      
        
        
//        [items enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            [menus enumerateObjectsUsingBlock:^(BizMenu * _Nonnull obj1, NSUInteger idx, BOOL * _Nonnull stop) {
//                [obj1.subclassArray enumerateObjectsUsingBlock:^(BizMenu *   _Nonnull obj3, NSUInteger idx, BOOL * _Nonnull stop) {
//                    if ([obj[@"ParentId"] isEqualToString: obj3.Id]) {
//                        if ([obj[@"Level"] integerValue] == 3) {
//                            [obj1.subclassArray1 addObject:[[BizMenu alloc] initWithDictionary:obj]];
//                        }
//                        
//                    }
//                }];
//                
//            }];
//        }];
        self.menus = menus;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
            [LoadingView dismiss];
        });
    }];
}

- (void)fetchCommunities {
    [self.communityWebService getCommunitiesByCityID:self.city.ID
                                              pageNo:@"1"
                                            pageSize:@"2"
                                   completionHanlder:^(NSArray *items, NSError *error) {
                                       if (error) {
                                           self.community = [[Community alloc] initWithName:@"请选择"];
                                       } else {
                                           self.community = [[Community alloc] initWithDictionary:[items firstObject]];
                                       }
                                       
                                           [self fetchBanners];
                                        [self fetchInfos];

                                   }];
}

- (void)fetchBanners {
    [self.bannerWebService getBannersByImageLevel:@"0" pageNo:@"" pageSize:@"" CommunityId:self.community.ID  completionHanlder:^(NSArray *items, NSError *error) {
        if (error) {
            
        } else {
            NSMutableArray<Banner *> *banners = NSMutableArray.new;
            for (NSDictionary *i in items) {
                [banners addObject:[[Banner alloc] initWithDictionary:i]];
            }
            self.banners = banners;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self updateBannerNoticeView];
                [self.collectionView reloadData];
            });
        }
    }];
}

- (void)fetchInfos {
    [self fetchInfosPagingEnabled:NO];
}

-(void)menusign{
    [self.menuSignWebService getMenuSignByCommunityId:self.community.ID completionHanlder:^(NSDictionary *items, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView.infiniteScrollingView stopAnimating];
        });
        if (error) {
            
        } else {
            _menuSign = [[MenuSign alloc]initWithDictionary:items];
            if (_buttons) {
                _buttons = nil;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.collectionView) {
//                    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
                                    [self.collectionView reloadData];

                }
                
            });
        }
    }];
}

- (void)fetchInfosPagingEnabled:(BOOL)flag {
    if (!flag) {
        self.pageIndex = 0;
    }
    [self.informationWebService getInfomationsByPageNo:@(self.pageIndex + 1) pageSize:@(self.pageSize) communityId:self.community.ID completionHanlder:^(NSArray *items, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView.infiniteScrollingView stopAnimating];
        });
        if (error) {
            
        } else {
            NSMutableArray<Information *> *infos = NSMutableArray.new;
            for (NSDictionary *i in items) {
                [infos addObject:[[Information alloc] initWithDictionary:i]];
            }
            if (flag) {
                self.infos = [[self.infos arrayByAddingObjectsFromArray:infos] mutableCopy];
            } else {
                self.infos = infos;
            }
            self.pageIndex ++;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
            });
        }
    }];
}

#pragma mark -

- (void)citySelectorDidSelectCity:(City *)city {
    self.city = city;
    [self fetchCommunities];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Delegate

- (void)selectorDidSelectCommunity:(Community *)item {
    self.community = item;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Private methods

- (void)setupDefaultCityAndCommunity {
    self.navigationItem.leftBarButtonItem.title = @"深圳";
    NSString *savedCityID = [UserInfoController defaultCityID];
    NSString *savedCityName = [UserInfoController defaultCityName];
    NSString *savedCommunityID = [UserInfoController defaultCommunityID];
    NSString *savedCommunityName = [UserInfoController defaultCommunityName];
    if (savedCityID.length) {
        self.city = [[City alloc] initWithID:savedCityID name:savedCityName];
    } else {
        self.city = [[City alloc] initWithName:@"请选择"];
        if ([CLLocationManager locationServicesEnabled]) {
            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
                [self.locationManager requestWhenInUseAuthorization];
            } else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
                [self.locationManager startUpdatingLocation];
            } else {
                [self fetchDetaultCity];
            }
        } else {
            [self fetchDetaultCity];
        }
    }
    if (savedCommunityID.length) {
        self.community = [[Community alloc] initWithID:savedCommunityID name:savedCommunityName];
    } else {
        self.community = [[Community alloc] initWithName:@"请选择"];
    }
    
    [self fetchBanners];
     [self fetchInfos];

    
}

- (void)registerCellIdentifiers {
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"BannerCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"HomeButtonsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"homeButtonsCell"];
    [self.collectionView registerClass:[HomeBizMenusCell class] forCellWithReuseIdentifier:@"HomeBizMenusCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"HomeInfoHeaderCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"infoHeaderCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"HomeInfosCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"infosCell"];
}

- (void)setupInfiniteScrolling {
//    [self.collectionView addInfiniteScrollingWithActionHandler:^{
//        [self loadMoreInfos];
//    }];
}

- (void)loadMoreInfos {
//    [self fetchInfosPagingEnabled:YES];
}

#pragma mark - Collection view datasource & delegates
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (section == 4) {
        return UIEdgeInsetsMake(8, 8, 0, 8);
    } else if (section == 3) {
        return UIEdgeInsetsMake(8, 0, 0, 0);
    } else if (section == 2) {
        return UIEdgeInsetsMake(10, 0, 0, 0);
    } else {
        return UIEdgeInsetsZero;
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 5;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 4) {
        return [self.infos count];
    } else if (section == 2){
        return [self.menus count];
    } else {
        return 1;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BannerCell" forIndexPath:indexPath];
        [cell.contentView addSubview:_bannerView];
        return cell;
        
        
    }
    else if (indexPath.section == 1) {
        HomeButtonsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"homeButtonsCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
        cell.items = self.buttons;
        cell.delegate = self;
        
        return cell;
    }
    else if (indexPath.section == 2) {
        
        HomeBizMenusCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeBizMenusCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
        cell.delegate = self;
        if (self.menus.count > 0) {
            [cell bindData:self.menus[indexPath.item]];
        }
        return cell;
    }
    else if (indexPath.section == 3) {
        HomeInfoHeaderCollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"infoHeaderCell" forIndexPath:indexPath];
        
        return cell;
    }
    else if (indexPath.section == 4) {
        HomeInfosCollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"infosCell" forIndexPath:indexPath];
        Information *i = self.infos[indexPath.item];
        [cell.imageView setOnlineImage:i.icon];
        cell.titleLabel.text = i.title;
        cell.aboutLabel.text = i.about;
        
        return cell;
    }
    else {
        return UICollectionViewCell.new;
    }
}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize boundsSize = collectionView.bounds.size;
    if (indexPath.section == 0) {
        if (self.banners.count > 0) {
            CGFloat width = boundsSize.width;
            CGFloat height = width / 2.5;
            return CGSizeMake(width, height);
        } else {
            return CGSizeMake(0.1, 0.1);
        }
    }
    else if (indexPath.section == 1) {
        return CGSizeMake(boundsSize.width, 80);
    }
    else if (indexPath.section == 2) {
        CGFloat width = boundsSize.width;
        return CGSizeMake(width, boundsSize.width / 3 * 0.7);
    }
    
    else if (indexPath.section == 3) {
        CGFloat width = boundsSize.width;
        CGFloat height = 30;
        return CGSizeMake(width, height);
    }
    else if (indexPath.section == 4) {
        CGFloat width = boundsSize.width / 2 - 12;
        CGFloat height = 140;
        return CGSizeMake(width, height);
    }
    return boundsSize;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 4) {
        
         Information *i = self.infos[indexPath.item];
        NSLog(@"%@,%@",i.linkType,i.linkUrl);
        if (i.linkUrl.length>0 && i.linkType != nil &&[i.linkType integerValue]>0) {
            
            ClientWebViewController *infoDetail = ClientWebViewController.new;
            infoDetail.hidesBottomBarWhenPushed = YES;
            infoDetail.title = @"活动详情";
            infoDetail.linkType = i.linkType;
            infoDetail.HTMLURL = i.linkUrl; //[NSString stringWithFormat:@"index/newsDetail.html?id=%@", i.ID];   //不配置，（linkType==1||==2）直接跳转到数据返回的地址
            [self.navigationController pushViewController:infoDetail animated:YES];
        }

        
    }
    
     
}

#pragma mark - segue

- (void)tryToShowFeedback {
    if ([UserInfoController isLogin]) {
        [self showFeedback];
    } else {
        [self pushLoginViewControllerCompletionHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }];
    }
}

- (void)showFeedback {
    [self performSegueWithIdentifier:@"showFeedback" sender:nil];
}

- (void)showPromotion {
    [self performSegueWithIdentifier:@"showPromotion" sender:nil];
}

- (void)tryToShowCouponCenter {
    if ([UserInfoController isLogin]) {
        [self showCouponCenter];
    } else {
        [self pushLoginViewControllerCompletionHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }];
    }
}

- (void)showCouponCenter {
    [self performSegueWithIdentifier:@"showCouponCenter" sender:nil];
}

- (void)tryToShowReward {
    if ([UserInfoController isLogin]) {
        [self showReward];
    } else {
        
        if ([_menuSign.CommonRepairSign isEqual:@"1"]) {
            [self pushLoginViewControllerCompletionHandler:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }];
        }
    }
}

- (void)showReward {
    
    UIStoryboard *s = [UIStoryboard storyboardWithName:@"ProjectsHelpers" bundle:nil];
    ProjectsHelpersViewController *phs = [s instantiateInitialViewController];
    phs.hidesBottomBarWhenPushed = YES;
   
    phs.bizType = BizTypeUnknow;
    phs.serviceID = serviceId;
    phs.serviceSubCategoryID = _publicMenus.ServiceCat2Id;
    phs.serviceName = _publicMenus.ModuleName;
    phs.communityId = self.community.ID;
    [self.navigationController pushViewController:phs animated:YES];
    
//    [self performSegueWithIdentifier:@"showReward" sender:nil];
}

- (void)tryToCollectBeans {
    if ([UserInfoController isLogin]) {
        [self collectBeans];
    } else {
        
        [self pushLoginViewControllerCompletionHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }];
    }
}

- (void)collectBeans {
    [LoadingView show];
    [self.beanWebService collectBeansCompletionHanlder:^(NSArray *items, NSError *error) {
        [LoadingView dismiss];
        if (error) {
            [LoadingView showToast:[error localizedDescription]];
        } else {
            NSString *msg = items.lastObject[@"resultMsg"];
            if ([msg respondsToSelector:@selector(length)] && msg.length > 0) {
                [LoadingView showToast:msg];
            } else {
                
                [LoadingView showToast:@"领取成功"];
            }
        }
    }];
}

#pragma mark ---HomeBizMenusCellDelegate
- (void)homeBizMenusCellClickWithModel:(BizMenu *)model withIndex:(NSInteger)index
{
    [self showUnknowForBizMenu:model withIndex:index];
}
 
- (void)showUnknowForBizMenu:(BizMenu *)m withIndex:(NSInteger)index
{
    if (![m.IsOpen boolValue]) {
        return;
    }
    if ([m.ServiceType integerValue] == 3) {
        ClientWebViewController *webViewController = ClientWebViewController.new;
        webViewController.hidesBottomBarWhenPushed = YES;
        webViewController.title = @"项目详情";
        //ff servicetype为123的情况 在判断一下 如果interLinkurl为空 然后就是之前的那种跳转 不为空的情况下  直接跳到interlinurl去
        NSString *url = m.InternalLink.length == 0 ? [NSString stringWithFormat:@"../projects/projectDetail.html?id=%@&pid=%@&cate1Id=%@", m.ServiceProductId, m.PriceId, m.ServiceCat1Id] :m.InternalLink;
        webViewController.HTMLURL = url;
        [self.navigationController pushViewController:webViewController animated:YES];
        
    }  else if ([m.ServiceType integerValue] == 2 || [m.ServiceType integerValue] == 1) {
        if(m.InternalLink.length > 0){
            ClientWebViewController *webViewController = ClientWebViewController.new;
            webViewController.hidesBottomBarWhenPushed = YES;
            webViewController.title = m.ModuleName;
            webViewController.HTMLURL = m.InternalLink;
            [self.navigationController pushViewController:webViewController animated:YES];
        } else {
            UIStoryboard *s = [UIStoryboard storyboardWithName:@"ProjectsHelpers" bundle:nil];
            ProjectsHelpersViewController *phs = [s instantiateInitialViewController];
            phs.hidesBottomBarWhenPushed = YES;
            if (index != 666666) {
                phs.menuData = m;
            }
            phs.bizType = BizTypeUnknow;
            phs.serviceID = m.ServiceCat1Id;
            phs.serviceSubCategoryID = m.ServiceCat2Id;
            phs.serviceName = m.ModuleName;
            phs.communityId = self.community.ID;
            [self.navigationController pushViewController:phs animated:YES];
        } 
    } else if ([m.ServiceType integerValue] == 4){
        
        ClientWebViewController *webViewController = ClientWebViewController.new;
        webViewController.hidesBottomBarWhenPushed = YES;
            webViewController.HTMLURL = m.ExternalLink;
            webViewController.title = m.ModuleName;
        [self.navigationController pushViewController:webViewController animated:YES];
        
    }
}

#pragma mark - User interactions

- (void)homeButtonTapped:(HomeButton *)button {
    [self performSelectorOnMainThread:button.selector withObject:nil waitUntilDone:YES];
}

- (IBAction)feedbackButtonTapped:(id)sender {
    [self tryToShowFeedback];
}

#pragma mark - Utils

- (void)payFinished:(NSNotification *)notification {
    if (self.tabBarController.selectedIndex != 0) {
        return;
    }
    ClientWebViewController *webViewController = ClientWebViewController.new;
    webViewController.hidesBottomBarWhenPushed = YES;
    NSNumber *userInfo = notification.object;
    if (!userInfo) {
        webViewController.HTMLURL = @"payment/finish.html";
    } else if ([userInfo respondsToSelector:@selector(boolValue)] && ![userInfo boolValue]) {
        webViewController.HTMLURL = @"payment/fail.html";
    }
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (CGFloat)heightForBizMenuViewWithCellHeight:(CGFloat)h {
    CGFloat padding = 10;
    CGFloat minHeight = h * 2 + padding * 2;
    if (self.menus.count < 1) {
        return 0;
    }
    if (self.menus.count < 4) {
        return minHeight;
    }
    return (ceil((self.menus.count - 3) / 2.0)) * (h + padding) + minHeight;
}

- (CGFloat)estimateHeightForBizMenuCellHeight {
    return 90;
}

#pragma mark - CLLocationManager delegate

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *newLocation = locations.firstObject;
    NSDate *eventDate = newLocation.timestamp;
    NSTimeInterval howRecent = [eventDate timeIntervalSince1970];
    if (self.lastUpdateTime == 0) {
        self.latitude = newLocation.coordinate.latitude;
        self.longitude = newLocation.coordinate.longitude;
        self.lastUpdateTime = howRecent;
        [self fetchDetaultCity];
    } else {
        if ((howRecent - self.lastUpdateTime) > 6) {
            [self.locationManager stopUpdatingLocation];
            self.locationManager = nil;
            self.latitude = newLocation.coordinate.latitude;
            self.longitude = newLocation.coordinate.longitude;
            self.lastUpdateTime = howRecent;
        }
    }
    
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    if (self.lastUpdateTime == 0) {
        [self fetchDetaultCity];
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self.locationManager startUpdatingLocation];
    } else if (status == kCLAuthorizationStatusDenied) {
        [self fetchDetaultCity];
    }
}

@end
